package com.sunyur.tailor.channel.common.middle.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sunyur.tailor.channel.common.middle.base.TokenUtilModel;
import com.sunyur.tailor.channel.common.middle.enums.MiddleResultEnum;
import com.sunyur.tailor.channel.common.middle.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Calendar;

/**
 *
 * @Author 99288
 * @Description 内部控制层拦截器，接口鉴权
 * @Date 15:00 2021/7/20
 * @Param
 * @return
**/
@Slf4j
public class InnerControllerHandler implements HandlerInterceptor {

    @Value("${sunyur.key}")
    private String appKey;
    @Value("${sunyur.secret}")
    private String appSecret;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//    	if(1==1)
//        {
//            return Boolean.TRUE;
//        }
        if("/outer/FS/Approval".equals( request.getServletPath()))
        {
            log.info("放行接口 {}",request.getServletPath());
            return Boolean.TRUE;
        }

        log.info("InnerControllerHandler preHandle path is {}", request.getServletPath());
    	String accessToken = request.getHeader("accessToken");
        log.info("InnerControllerHandler preHandle accessToken:{}", accessToken);
        if(StringUtils.isEmpty(accessToken)){
            setResponse(response, MiddleResultEnum.BAD_GATEWAY.getCode(), MiddleResultEnum.BAD_GATEWAY.getValue());
            return Boolean.FALSE;
        }
        //解密令牌
        TokenUtilModel tokenUtilModel = TokenUtil.decryptToken(accessToken, appSecret);

        // 验证时间戳
        Calendar c = Calendar.getInstance();
        long nowTimestamp = c.getTimeInMillis()/1000;
        long reqTimestamp = tokenUtilModel.getExpireTime();
        /**
         * 有效时间30分钟
         */
        long time = 60 * 30L;
        if ( nowTimestamp-reqTimestamp > time){
            setResponse(response, MiddleResultEnum.UNAUTHORIZED.getCode(), MiddleResultEnum.UNAUTHORIZED.getValue());
            return Boolean.FALSE;
        }

        //校验appKey、secret
        if (!appKey.equals(tokenUtilModel.getClientId()) || !appSecret.equals(tokenUtilModel.getClientSecret())){
            setResponse(response, MiddleResultEnum.PAYMENT_REQUIRED.getCode(), MiddleResultEnum.PAYMENT_REQUIRED.getValue());
            return Boolean.FALSE;
        }

        return Boolean.TRUE;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
    /**
     * response 返回参数
     */
    private void setResponse(HttpServletResponse response, String code, String msg){
        PrintWriter out = null ;
        try{
            response.setContentType("application/json; charset=utf-8");
            JSONObject res = new JSONObject();
            res.put("code",code);
            res.put("msg",msg);
            out = response.getWriter();
            out.write(res.toString());
            out.flush();
            log.info("InnerControllerHandler setResponse is error result {}", JSON.toJSONString(res) );
        }catch (Exception e){
            log.error("InnerControllerHandler setResponse is Exception {}",e);
        }finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
